package com.gonsin.ta.logic.parse.operator;

import cn.hutool.core.util.ArrayUtil;
import com.gonsin.ta.logic.node.SignalNodeAdapter;
import com.gonsin.ta.logic.parse.Chain;
import com.gonsin.ta.logic.exceptions.TaException;
import com.gonsin.ta.logic.parse.condition.Condition;
import com.gonsin.ta.logic.parse.condition.WaitCondition;
import com.gonsin.ta.logic.node.Node;
import com.gonsin.ta.logic.enums.NodeTypeEnum;
import com.gonsin.ta.logic.process.SignalCenter;
import com.ql.util.express.Operator;

/**
 * 运行节点
 */
public class WaitOperator extends Operator {

    private Chain chain;

    private SignalCenter signalCenter;

    public WaitOperator(Chain chain, SignalCenter signalCenter) {
        this.chain = chain;
        this.signalCenter = signalCenter;
    }

    @Override
    public Object executeInner(Object[] objects) throws Exception {

        validate(objects);
        Long timeout = null;
        if(objects.length > 1){
//            if(objects[1] instanceof String){
//                // TODO 后期可以自定义时间解析器
//                timeout = new SimpleDateFormat("HH:mm:ss").parse(String.valueOf(objects[1])).getTime();
//            } else
            if(objects[1] instanceof Integer) {
                timeout = (long) (int) objects[1];

                return new WaitCondition((SignalNodeAdapter) objects[0], timeout, signalCenter);
            } else if(objects[1] instanceof String){
                String dynamicTimeout = (String) objects[1];
                if(dynamicTimeout.startsWith("$")){
//                    dynamicTimeout = dynamicTimeout.substring(1, dynamicTimeout.length() - 1);
                    return new WaitCondition((SignalNodeAdapter) objects[0], dynamicTimeout, signalCenter);
                }
            }
            throw new TaException("chain id = {}, WATI方法第二个参数只能接收字符串或int类型，或者以freemarker语法表示的动态模板例如 \"${AUDIT_TIMEOUT}\"，表示等待的秒数", chain.getChainId());
        }

        Condition result = new WaitCondition((SignalNodeAdapter) objects[0], signalCenter);
        return result;
    }

    private void validate(Object[] objects){
        if (ArrayUtil.isEmpty(objects)){
            throw new TaException("chain id = {}, WAIT方法必须至少包含一个参数", chain.getChainId());
        }

        if (objects.length > 2){
            throw new TaException("chain id = {}, WAIT方法最多只能包含2个参数", chain.getChainId());
        }

        if(!(objects[0] instanceof Node)){
            throw new TaException("chain id = {}, WAIT方法的第1个参数必须是组件", chain.getChainId());
        }
        Node node = (Node) objects[0];
        if(node.getNodeType() != NodeTypeEnum.SIGNAL){
            throw new TaException("chain id = {}, WAIT方法的第1个参数必须是信号组件", chain.getChainId());
        }
    }
}
